<template>
    <div>
        <form class="studentForm">
            <input v-model="formData.id" type="hidden" class="studentIdToEdit" />

            <label for="studentName">Name</label>
            <input v-model="formData.name" type="text" name="name" class="studentName" required />

            <label for="studentGender">Gender</label>
            <select v-model="formData.gender" name="gender" class="studentGender" required>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select>

            <label for="studentHobbies">Hobbies</label>
            <input v-model="formData.hobbies" type="text" name="hobbies" class="studentHobbies" required />

            <label for="studentEmail">Email</label>
            <input v-model="formData.email" type="email" name="email" class="studentEmail" required />

            <label for="studentPhone">Phone</label>
            <input v-model="formData.phone" type="text" name="phone" class="studentPhone" required />

            <label for="studentAge">Age</label>
            <input v-model="formData.age" type="number" name="age" class="studentAge" required />

            <button @click.prevent="saveStuInfo" type="submit" class="saveStudentBtn">保存学生信息</button>
        </form>
    </div>
</template>

<script setup lang='ts'>
import { ref, toValue, watch } from 'vue';
// 学生信息接口
export interface IStudent {
    id: string,
    name: string,
    gender: string,
    hobbies: string,
    email: string,
    phone: string,
    age: number | string,
    create_at?: string,
    update_at?: string,
    seleted?: boolean
}

// 定义部分学生学校类型
export type PIStudent = Partial<IStudent>

// 定义组件属性，接收一个学生信息对象
const props = defineProps<{
    userInfo: IStudent
}>()

// 表单数据对象
const formData = ref<PIStudent>(props.userInfo)


// 定义事件发射器，用于发射保存事件
const emit = defineEmits<{
    (e: 'save', userInfo: IStudent): void
}>()

// 日志输出接收到的用户信息 props.userInfo
console.log(props.userInfo, 'userInfo');

// 保存学生信息函数
const saveStuInfo = () => {
    // 发射保存事件，携带表单数据
    emit('save', formData.value as IStudent)
    // 日志输出当前表单数据
    console.log(formData.value, 'formData.value');
}

// 监听props中 props.userInfo变化，更新formData
watch(
    () => toValue(props.userInfo),
    () => {
        // 当props中的 props.userInfo变化时，更新formData的值
        formData.value = props.userInfo
        // 日志输出更新后的 props.userInfo
        console.log(props.userInfo, 'watch:props.userInfo');
    }
)


</script>

<style lang="scss" scoped>
label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

input,
select {
    width: 100%;
    padding: 8px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

.saveStudentBtn {
    background-color: #4caf50;
    color: #fff;
    padding: 10px;
    font-size: 16px;
    border-radius: 4px;
    width: 100%;

    &:hover {
        background-color: #45a049;
    }
}
</style>